package com.test.config;

import com.google.common.collect.Range;
import lombok.extern.log4j.Log4j2;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.stream.Collectors;

@Log4j2
public class DateRangeShardingAlgorithm implements RangeShardingAlgorithm<Date> {

    private static Map<String, Integer> map = new HashMap();


    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, RangeShardingValue<Date> rangeShardingValue) {
        List<String> list = new ArrayList<>();
        log.info("availableTargetNames : " + availableTargetNames);
        log.info(rangeShardingValue.toString());
        Range<Date> valueRange = rangeShardingValue.getValueRange();
        Date lowerDate = valueRange.lowerEndpoint();
        Date upperDate = valueRange.upperEndpoint();

       // LocalDateTime dateTime =LocalDateTime.ofEpochSecond(date.getTime()/1000,0, ZoneOffset.ofHours(8));
        LocalDateTime lowerLocalDateTime = LocalDateTime.ofEpochSecond(lowerDate.getTime()/1000,0, ZoneOffset.ofHours(8));
        Integer lowerYear = lowerLocalDateTime.getYear();
        Integer lowerMonth = lowerLocalDateTime.getMonth().getValue();

        LocalDateTime upperDateLocalDateTime = LocalDateTime.ofEpochSecond(upperDate.getTime()/1000,0, ZoneOffset.ofHours(8));
        Integer upperYear = upperDateLocalDateTime.getYear();
        Integer upperMonth = upperDateLocalDateTime.getMonth().getValue();
        List<String> availableTargetList = availableTargetNames.stream().collect(Collectors.toList());
        if (CollectionUtils.isEmpty(map)) {
            for (int i = 0; i < availableTargetList.size(); i++) {
                map.put(availableTargetList.get(i), i);
            }
        }
        Integer start = 0;
        Integer end = 0;
        if (lowerMonth <= 6) {
            start = map.get("t_order_" + lowerYear + "_1");
        } else {
            start = map.get("t_order_" + lowerYear + "_2");
        }
        if (upperMonth <= 6) {
            end = map.get("t_order_" + upperYear + "_1");
        } else {
            end = map.get("t_order_" + upperYear + "_2");
        }
        for (int i = start; i <= end; i++) {
            list.add(availableTargetList.get(i));
        }
        log.info("match tableNames-----------------------" + list.toString());
        return list;
    }

}
